const BaseMonitor = require('./base-monitor');

class TemperatureMonitor extends BaseMonitor {
  constructor(deviceId, mqttConnector) {
    super(deviceId, mqttConnector);
    this.topic = 'device/temperature';
    this.temperature = '0';
    this.unit = '℃';
    this.status = 'normal';

    // 注册消息处理
    this.onMessage(this.topic, this.handleTemperatureMessage.bind(this));
  }

  // 初始化
  async init() {
    await this.subscribe(this.topic);
    console.log('温度传感器监控模块已初始化');
  }

  // 处理温度消息
  handleTemperatureMessage(message) {
    try {
      // 只处理JSON格式消息（已在mqtt-connector中解析）
      if (typeof message === 'object' && message.type === 'sensor-data' && message.data) {
        this.temperature = message.data.value;
        this.unit = message.data.unit || '℃';
        this.status = message.data.status || 'normal';

        // 格式化温度值为2位小数，并添加时间戳
        const formattedTemperature = this.temperature;
        const timestamp = new Date(message.timestamp).toLocaleString();
        console.log(`[温度传感器] 时间: ${timestamp}, 设备ID: ${message.deviceId}, 当前温度: ${formattedTemperature}${this.unit}, 状态: ${this.status}`);

        // 触发数据更新事件（如果有监听器）
        if (this.onUpdate) {
          this.onUpdate({
            deviceId: message.deviceId,
            timestamp: message.timestamp,
            value: this.temperature,
            unit: this.unit,
            status: this.status
          });
        }
      } else {
        console.log(`无效的温度消息格式: ${JSON.stringify(message)}`);
      }
    } catch (error) {
      console.error(`处理温度消息错误: ${error.message}`);
    }
  }

  // 获取当前温度数据
  // 在TemperatureMonitor类中添加
  // 修正getCurrentData方法
  async getCurrentData() {
    return {
      deviceId: this.deviceId,
      value: this.temperature,  
      unit: this.unit,
      status: this.status,
      timestamp: Date.now()
    };
  }
}

module.exports = TemperatureMonitor;